# 用户登录
from rest_framework.views import APIView
from utils.config import Config
from utils.result import R
from utils.aliverify_code import * 
from api.models import ItEduUser,ItEduLessonVideoSet



class UserAPIView(APIView):

    """
    获取所有优质用户数量
    """
    def get(self,request,*args, **kwargs):

        total_num = ItEduUser.objects.filter(score__gte=Config.GOOD_USER_MIN_SCORE,vip_type="创作者会员").count()

        return R().data_result(total_num=total_num)

    """
    获取优质用户数据
    排序按分数的多少由大到小
    """
    def post(self,request,*args, **kwargs):
        offset = request.data.get("offset",0)
        limit = request.data.get("limit",10)

        if limit > 30:
            return R.params_error().to_json_response()

        good_user_list = list(ItEduUser.objects.filter(score__gte=Config.GOOD_USER_MIN_SCORE,vip_type="创作者会员").order_by("-score","-_id")[offset:offset+limit].values(
            "avatar_image",
            "nickname",
            "intro",
            "_id"
        ))

        for user in good_user_list:
            user["lesson_set_num"] = ItEduLessonVideoSet.objects.filter(author___id=user["_id"]).count()


        return R().data_result(good_user_list=good_user_list)

    """
    根据用户ID获取用户信息用于视频播放页面展示
    """
    def put(self,request,*args, **kwargs):
        user_pk = request.data.get("user_pk")
        
        user = list(ItEduUser.objects.filter(pk=user_pk).values("nickname","avatar_image","intro"))[0]

        return R().data_result(user=user)
    
class UserInfoAPIView(APIView):

    def put(self,request,*args, **kwargs):

        user_pk = request.session.get("user_pk")

        avatar_image = request.date.get("avatar_image",None)
        nickname = request.data.get("nickname",None)
        intro = request.data.get("intro",None)

        if not avatar_image:
            ItEduUser.objects.filter(pk=user_pk).update(avatar_image=avatar_image)
        if not nickname:
            ItEduUser.objects.filter(pk=user_pk).update(nickname=nickname)
        if not intro:
            ItEduUser.objects.filter(pk=user_pk).update(intro=intro)

        return R.ok().to_json_response()


